<template>
  <div class="exam-questions">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试题目设置</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>
      <div class="questions-content">
        <div class="questions-list">
          <h3>可选题库</h3>
          <el-input v-model="search" placeholder="搜索题目" class="search-input" />
          <el-table :data="filteredQuestions" height="400">
            <el-table-column prop="title" label="题目" />
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button size="small" @click="addQuestion(row)">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="assigned-list">
          <h3>本考试题目（可拖拽排序）</h3>
          <draggable v-model="assignedQuestions" item-key="id" animation="200">
            <template #item="{ element, index }">
              <div class="draggable-item">
                <span>{{ index + 1 }}. {{ element.title }}</span>
                <el-button size="small" @click="removeQuestion(element)">移除</el-button>
              </div>
            </template>
          </draggable>
          <el-button type="primary" class="save-btn" @click="saveQuestions">保存</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import draggable from 'vuedraggable'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

const search = ref('')
const allQuestionsFromApi = ref<any[]>([])
const assignedQuestions = ref<any[]>([])

const fetchQuestions = async () => {
  const examId = route.params.id
  if (!examId || isNaN(Number(examId))) {
    // 给出提示或不发请求
    return
  }
  const res = await axios.get(`/api/exams/${examId}/questions/all`, { params: { keyword: search.value } })
  allQuestionsFromApi.value = res.data.data || []
  console.log('assignedQuestions:', assignedQuestions.value)
  console.log('allQuestionsFromApi:', allQuestionsFromApi.value)
}

const filteredQuestions = computed(() =>
  allQuestionsFromApi.value.filter(q =>
    q.title.includes(search.value) &&
    !assignedQuestions.value.some(a => Number(a.id) === Number(q.id))
  )
)

const addQuestion = (q: any) => {
  assignedQuestions.value.push({ id: q.id, title: q.title })
}
const removeQuestion = (q: any) => {
  assignedQuestions.value = assignedQuestions.value.filter(a => a.id !== q.id)
}
const saveQuestions = async () => {
  const examId = route.params.id
  try {
    await axios.put(`/api/exams/${examId}/questions`, assignedQuestions.value)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存考试题目失败:', error)
    ElMessage.error('保存考试题目失败')
  }
}
const handleBack = () => {
  router.back()
}

onMounted(async () => {
  const examId = route.params.id
  try {
    const response = await axios.get(`/api/exams/${examId}/questions`)
    if (Array.isArray(response.data.data)) {
      assignedQuestions.value = (response.data.data as Array<{id?: number, questionId?: number, title: string}>).map((q: {id?: number, questionId?: number, title: string}) => ({
        id: q.questionId ?? q.id,
        title: q.title
      }))
    } else {
      assignedQuestions.value = []
    }
    // 回显后再拉题库，确保左侧排除右侧已选
    await fetchQuestions()
  } catch (error) {
    console.error('获取考试题目失败:', error)
    ElMessage.error('获取考试题目失败')
  }
})

watch(search, fetchQuestions)
</script>

<style scoped>
.exam-questions {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.questions-content {
  display: flex;
  gap: 40px;
  margin-top: 20px;
}
.questions-list, .assigned-list {
  flex: 1;
  min-width: 0;
}
.search-input {
  margin-bottom: 10px;
  width: 100%;
}
.save-btn {
  margin-top: 16px;
  width: 100%;
}
.draggable-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}
</style>
